package com.yanchi;


import com.yanchi.realm.MD5CustomRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

/**
 * 测试自定义 Realm（加密版）
 */
public class TestMD5Custom {
    public static void main(String[] args) {

        // 1、创建安全管理器对象
        DefaultSecurityManager securityManager = new DefaultSecurityManager();

        // 2、给安全管理器设置realm
        MD5CustomRealm realm = new MD5CustomRealm();    // 自定义的Realm

        // 创建凭证匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        // 设置MD5加密
        matcher.setHashAlgorithmName("md5");
        // 设置散列次数
        matcher.setHashIterations(1024);

        // 设置安全管理器的凭证匹配器
        realm.setCredentialsMatcher(matcher);
        securityManager.setRealm(realm);

        // 3、给全局安全管理器设置安全管理器
        SecurityUtils.setSecurityManager(securityManager);

        // 4、获取关键对象subject主体
        Subject subject = SecurityUtils.getSubject();

        // 5、创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken("yanchi","123456");

        try {
            subject.login(token);
            System.out.println("登录成功！");
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("登录失败：账号不存在");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("登录失败：密码错误");
        }catch (Exception e){
            e.printStackTrace();
        }

        // 基于角色的访问控制
        System.out.println("\n \n====== 基于角色的访问控制 ======");
        System.out.println("admin角色权限：" + subject.hasRole("admin"));
        System.out.println("user角色权限：" + subject.hasRole("user"));
        System.out.println("super角色权限：" + subject.hasRole("super"));

        boolean[] b1 = subject.hasRoles(Arrays.asList("admin", "super", "user"));
        System.out.println("角色权限：" + Arrays.toString(b1));

        boolean b2 = subject.hasAllRoles(Arrays.asList("admin", "super", "user"));
        System.out.println("同时满足所有角色：" + b2);

        // 基于资源的访问控制
        System.out.println("\n \n====== 基于资源的访问控制 ======");
        System.out.println("资源权限：" + subject.isPermitted("user:create:001"));
        System.out.println("资源权限：" + subject.isPermitted("admin:create:001"));
        System.out.println("资源权限：" + subject.isPermitted("user:update:001"));

        boolean[] b3 = subject.isPermitted("user:create:001", "admin:create:001", "user:update:001");
        System.out.println("资源权限：" + Arrays.toString(b3));

        boolean b4 = subject.isPermittedAll("user:create:001", "admin:create:001", "user:update:001");
        System.out.println("同时满足所有资源权限：" + b4);


    }
}
